package com.weixin.gong.example.umeng;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: gongweixin
 * Date: 14-7-21
 * Time: 下午2:02
 * To change this template use File | Settings | File Templates.
 */
public class Push {
	private static final String app_master_secret = "vs2ujihvyfjgz2jwpioiv1appx2mhkho";
	private static final String push_type_unicast = "unicast";
	private final String URL = "http://msg.umeng.com/api/send";
	private final String appkey = "5357a2e656240bae4d0146fb";
	private String timestamp;
	private String validation_token;
	private String type;
	private String device_tokens;
	private String alias;
	private String file_id;
	private String filter;
	private Payload payload;
	private Policy policy;
	private String production_mode;
	private String feedback;
	private String description;
	private String thirdparty_id;

	private Push() {
		timestamp = String.valueOf(new Date().getTime());
		validation_token =  DigestUtils.md5Hex(appkey.toLowerCase() +
				app_master_secret.toLowerCase() + timestamp);
	}

	public static Push unicast(String device_tokens) {
		Push unicast = new Push();
		unicast.type = push_type_unicast;
		unicast.device_tokens = device_tokens;
		return unicast;
	}

	public void setPayload(Payload payload) {
		this.payload = payload;
	}

	public boolean send() {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URL);
		try {
			String resultJson = JSONObject.toJSONString(this);
			System.out.println(resultJson);
			StringEntity s = new StringEntity(resultJson);
			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");
			post.setEntity(s);
			HttpResponse res = client.execute(post);
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
				while (rd.read() != -1) {
					System.out.println(rd.readLine());
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean send(Payload payload) {
		this.payload = payload;
		return send();
	}

	public class Policy {
		private String start_time;
		private String expire_time;
		private Integer max_send_num;
	}
}
